package com.xtaller.sdboot.core.base;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.sdboot.utils.helper.JsonHelper;
import com.xtaller.sdboot.utils.helper.ValidatorHelper;
import com.baomidou.mybatisplus.annotation.TableField;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Taller
 * @date : 2020/2/6 14:51
 * @Description : 附带Ext扩展字段的Entity父类
 */
public abstract class BaseExtEntity extends BaseEntity {
    @TableField
    private String ext; //扩展数据

    @TableField(exist = false)
    private Map<String, Object> ExtMap;

    public String getExt() {
        if(ValidatorHelper.isEmpty(this.ExtMap)){
            return null;
        }
        return JsonHelper.toJSONString(this.ExtMap);
    }

    public JSONObject getJsonExt(){
        if(ValidatorHelper.isEmpty(this.ext)){
            return JsonHelper.create();
        }
        return JsonHelper.o2j(this.ext);
    }

    public List<JSONObject> getListJsonExt(){
        if(ValidatorHelper.isEmpty(this.ext)){
            return JsonHelper.list();
        }
        return JsonHelper.o2l(this.ext);
    }

    public BaseExtEntity setExt(String Ext) {
        if(ValidatorHelper.notEmpty(Ext)){
            this.ExtMap = JsonHelper.toLinkedHashMap(Ext);
        }
        return this;
    }

    /***
     * 从Ext JSON中提取扩展属性值
     * @param extAttrName
     * @return
     */
    public Object getFromExt(String extAttrName){
        if(this.ExtMap == null){
            return null;
        }
        return this.ExtMap.get(extAttrName);
    }

    /***
     * 添加扩展属性和值到Ext JSON中
     * @param extAttrName
     * @param extAttrValue
     */
    public BaseExtEntity addIntoExt(String extAttrName, Object extAttrValue){
        if(extAttrName == null && extAttrValue == null){
            return this;
        }
        if(this.ExtMap == null){
            this.ExtMap = new LinkedHashMap<>();
        }
        this.ExtMap.put(extAttrName, extAttrValue);
        return this;
    }

}
